<script lang="ts" setup>
import { getFile } from '@/api/FileApi.ts'
import { encode } from 'js-base64'
import { onBeforeUnmount, ref, watch } from 'vue'

const props = defineProps<{
    uri: string
}>()

const isLoading = ref(false)
const url = ref('')
let isObjectUrl = false

const httpUrl = new RegExp('http(s)?://.*')
const blobHttp = new RegExp('blob:http(s)?.*')

const readResource = () => {
    const uri = props.uri
    if (!uri) {
        return
    }

    if (httpUrl.test(uri) || blobHttp.test(uri)) {
        url.value = uri
        return
    }

    isLoading.value = true
    getFile(encode(uri), false)
            .then(res => {
                if (res instanceof Blob) {
                    url.value = window.URL.createObjectURL(res)
                    isObjectUrl = true
                } else {
                    url.value = res.url
                    isObjectUrl = false
                }
            })
            .catch(err => console.debug(`加载资源 ${ uri } 失败!`, err))
            .finally(() => isLoading.value = false)
}

watch(() => props.uri, readResource, { immediate: true })
onBeforeUnmount(() => {
    if (isObjectUrl) {
        window.URL.revokeObjectURL(props.uri)
    }
})
</script>

<template>
<slot :isLoading="isLoading" :url="url" />
</template>

<style lang="scss" scoped>

</style>
